<?php
/**
 * Created by PhpStorm.
 * User: zws
 * Date: 2018/9/8
 * Time: 11:02
 * 检测人员管理
 */
namespace app\index\service;

use app\common\model\MachineModel;
use app\common\model\ModuleModel;
use app\common\model\OperateModel;
use app\common\model\ProtectModel;
use think\Exception;
use think\Db;
class ProtectService
{
    protected static $protectModel;
    protected static $operateModel;
    protected static $moduleModel;

    /**
     * zws
     * ProtectService constructor.
     * @param ProtectModel $protectModel
     * @param OperateModel $operateModel
     */
    public function __construct(ProtectModel $protectModel, OperateModel $operateModel, ModuleModel $moduleModel)
    {
        self::$protectModel = $protectModel;
        self::$operateModel = $operateModel;
        self::$moduleModel = $moduleModel;
    }

    /**
     * zws
     * 上传变电站
     * @param $request
     * @return array
     */
    public function upload_protect($request)
    {
        if(empty($request->res_code)){
            app_fail(8599);
        }
        if(empty($request->res_name)){
            app_fail(8598);
        }
        if(empty($request->res_detail)){
            app_fail(8597);
        }
        $protectModel = self::$protectModel;
        $protect_data = $protectModel->where('res_code', '=', $request->res_code)->find();
        if($protect_data)
        {
            app_fail(8596);
        }
//        $img_url = '';
//        if($request->image)
//        {
//            $img_url = $this->uploadImage($request->image);
//        }
        $data = array(
            'res_code'=>$request->res_code,
            'res_name'=>$request->res_name,
            'user_id'=>$request->tokenId,
            'station_id'=>($request->station_id) ? $request->station_id : '',
            'res_detail'=>$request->res_detail,
//            'imgurl'=>$img_url ? $img_url : '',
            'remark'=>$request->remark,
            'create_time'=>time(),
            'update_time'=>time(),
        );
        Db::startTrans();
        try{
            $operate_data = self::$operateModel->where(['res_code'=>$request->res_code,
                'user_id'=>$request->tokenId])->find();
            if(!$operate_data)
            {
                $add_operate_data = [
                    'res_code' => $request->res_code,
                    'user_id' => $request->tokenId,
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                self::$operateModel->save($add_operate_data);
            }
            $protectModel->save($data);
            Db::commit();
            return ['res_id'=>$protectModel->id];
        }catch (Exception $e){
            Db::rollback();
            app_fail(9899);//编辑失败
        }
    }

    /**
     * zws
     * 上传图片
     * @param $file
     * @return string
     */
    public function uploadImage($file)
    {
        $imagePath = config('param_config.imagePath');
        $img_url = '';
        // 移动到框架应用根目录/uploads/ 目录下
        $info = $file->validate(['ext'=>'jpeg,jpg,png,gif'])->move($imagePath);
        if($info){
            $img_url = $info->getSaveName();
        }else{
            // 上传失败获取错误信息
            app_fail($file->getError());
        }
        return $img_url;
    }


    /**
     * zws
     * 获取保护列表
     * @param $request
     * @return array
     */
    public function protect_list($request)
    {
        if(empty($request->page))
        {
            $request->page = 1;
        }
        if(empty($request->limit))
        {
            $request->limit = 20;
        }
        $type = $request->role;
        $where = '';
        if($type == 2)
        {
            $where1 = [
                ['user_id', '=', $request->tokenId],
                ['res_code', '<>', ''],
            ];
            if($request->page > 0) {
                $res_code_arr = self::$operateModel->where($where1)
                    ->distinct(true)
                    ->field('res_code')
                    ->page($request->page, $request->limit)
                    ->column('res_code');
            }else{
                $res_code_arr = self::$operateModel->where($where1)
                    ->distinct(true)
                    ->field('res_code')
                    ->column('res_code');
            }
            $res_code_str = "'".implode("','", $res_code_arr)."'";
            $where = " res_code in ($res_code_str) or user_id = ".$request->tokenId;
        }

        $count = self::$protectModel->where($where)
            ->count();
        if ($count < 1) {
            return ['links' => [], 'count' => $count];
        }
        if($request->page > 0)
        {
            $result = self::$protectModel->where($where)
                ->page($request->page, $request->limit)
                ->order('create_time', 'desc')
                ->select();
        }else
        {
            $result = self::$protectModel->where($where)
                ->order('create_time', 'desc')
                ->select();
        }
        if($result)
        {
            foreach ($result as $k=>$v)
            {
                $result[$k]->date = date('Y-m-d H:i:s', $v['create_time']);
                $result[$k]->res_limit = 0;
                if($type == 1)
                {
                    $result[$k]->res_limit = 1;
                }else
                {
                    if($request->tokenId == $v['user_id'])
                    {
                        $result[$k]->res_limit = 1;
                    }
                }
            }
        }
        return ['links' => $result, 'count' => $count];
    }

    /**
     * 获取保护详情
     * @param $request
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public function protect_detail($request)
    {
        if(empty($request->res_code))
        {
            app_fail(8599);
        }
        $res_data = self::$protectModel->where(['res_code'=>$request->res_code])->find();
        $res_data -> date = date("Y-m-d H:i:d", $res_data->create_time);
        $res_data->res_limit = 0;
        return $res_data;

    }

    /***
     * zws
     * 根据变电站id获取保护信息
     * @param $request
     * @return array
     */
    public function station_protect($request)
    {
        if(empty($request->page))
        {
            $request->page = 1;
        }
        if(empty($request->limit))
        {
            $request->limit = 20;
        }
        if(empty($request->station_id))
        {
            app_fail(8997);
        }
        $type = $request->role;

        $count = self::$protectModel->where(['station_id'=>$request->station_id])->count();
        if ($count < 1) {
            return ['links' => [], 'count' => $count];
        }
        if($request->page > 0)
        {
            $result = self::$protectModel->where(['station_id'=>$request->station_id])
                ->page($request->page, $request->limit)
                ->order('create_time', 'desc')
                ->select();
        }else
        {
            $result = self::$protectModel
                ->where(['station_id'=>$request->station_id])
                ->order('create_time', 'desc')
                ->select();
        }
        if($result)
        {
            foreach ($result as $k=>$v)
            {
                $result[$k]->date = date('Y-m-d H:i:s', $v['create_time']);
                $result[$k]->res_limit = 0;
                if($type == 1)
                {
                    $result[$k]->res_limit = 1;
                }else
                {
                    if($type == 2 && $request->tokenId == $v['user_id'])
                    {
                        $result[$k]->res_limit = 1;
                    }
                }
            }
        }
        return ['links' => $result, 'count' => $count];
    }

    /**
     * zws
     * 修改保护的变电站
     * @param $request
     * @return array
     */
    public function update_protect($request)
    {
        if(empty($request->station_id))
        {
            app_fail(8997);
        }
        if(empty($request->res_code)){
            app_fail(8599);
        }
        $protect_data = self::$protectModel
            ->where(['res_code'=>$request->res_code])->find();
        if(empty($protect_data))
        {
            app_fail(8595);
        }
        if($request->role != 1 && ($request->role != 2 || $request->tokenId != $protect_data->user_id))
        {
            app_fail(9984);
        }
        try{
            self::$protectModel->save(['station_id'=>$request->station_id], ['res_code'=>$request->res_code]);
            return [];
        }catch (Exception $e){
            app_fail(9899, $e->getMessage());//编辑失败
        }
    }

    /**
     * zws
     * 删除模板、保护、测试仪
     * @param $params
     * @return bool
     */
    public function del_data($params)
    {
        if(empty($params))
        {
            app_fail(9997);
        }
        if(!isset($params['type']) || (empty($params['type']) && $params['type'] !== '0'))
        {
            app_fail(8590);
        }
        if(!isset($params['id']) || !$params['id'])
        {
            app_fail();
        }
        if($params['type'] == 1)
        {
           //保护
            return $this->del_protect($params);
        }elseif ($params['type'] == 2)
        {
            //测试仪
            return $this->del_machine($params);
        }else
        {
            //模块
            return $this->del_module($params);
        }
    }

    public function del_protect($params)
    {
        $protect_data = self::$protectModel->where(['res_code'=>$params['id']])->find();
        if(empty($protect_data))
        {
            app_fail(8595);
        }
        //保护
        if($params['role'] == 2)
        {
            if($protect_data->user_id != $params['tokenId'])
            {
                app_fail(9985);
            }
        }
        try{
            $result = self::$protectModel->where(['res_code'=>$params['id']])->delete();
            return $result ? true : false;
        }catch (Exception $e){
            app_fail(9980);//编辑失败
        }
    }

    public function del_machine($params)
    {
        if($params['role'] != 1)
        {
            app_fail(9985);
        }
        $machineModel = new MachineModel();
        $machine_data = $machineModel->where(['machine_code'=>$params['id']])->find();
        if(empty($machine_data))
        {
            app_fail(8298);
        }
        try{
            $result = $machineModel->where(['machine_code'=>$params['id']])->delete();
            // 同时删除模块
            self::$moduleModel->where('machine_code', '=', $machine_data['machine_code'])->delete();
            return $result ? true : false;
        }catch (Exception $e){
            app_fail(9980);//编辑失败
        }
    }

    public function del_module($params)
    {
        if($params['role'] != 1)
        {
            app_fail(9985);
        }
        $moduleModel = new ModuleModel();
        $module_data = $moduleModel->where(['module_code'=>$params['id']])->find();
        if(empty($module_data))
        {
            app_fail(8296);
        }
        try{
            $result = $module_data->where(['module_code'=>$params['id']])->delete();
            return $result ? true : false;
        }catch (Exception $e){
            app_fail(9980);//编辑失败
        }
    }
}